package org.noote.libs.computervision.function;

public class Otsu {

	static public int findThresholding(float pLevels[])
	{
		int iRet = 0;
		float fS, fMax=0.0f;
		float fCumul[] = new float[pLevels.length], fMoy[] = new float[pLevels.length];

		fCumul[0] = pLevels[0];
		fMoy[0] = 0.0f;

		for(int i=1; i<pLevels.length; i++)
		{
			fCumul[i]=fCumul[i-1]+pLevels[i];
			fMoy[i]=fMoy[i-1]+pLevels[i]*i; 
		}

		for(int i=0; i<pLevels.length; i++)
		{
			fS=fCumul[i]*(1.0f-fCumul[i])*(float)Math.pow((fMoy[pLevels.length]*fCumul[i]-fMoy[i]), 2.0f);
			if(fS>fMax)
			{
				fMax = fS;
				iRet = i;
			}
		}

		return iRet;
	}
}
